package com.mworld.galaxy.bull.web.account;

import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mworld.galaxy.base.service.account.ShiroDbRealm.ShiroUser;
import com.mworld.galaxy.bull.entity.MemberUser;
import com.mworld.galaxy.bull.service.account.MemberAccountService;

/**
 * 用户修改自己资料的Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/member/login-profile")
public class ProfileController {

    @Autowired
    private MemberAccountService memberAccountService;

    @RequestMapping(method = RequestMethod.GET)
    public String updateForm(Model model) {
        Long id = getCurrentUserId();
        model.addAttribute("user", memberAccountService.getUser(id));
        return "/member/login-profile";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("preloadUser") MemberUser user) {
        memberAccountService.updateUser(user);
        updateCurrentUserName(user.getName());
        return "redirect:/";
    }

    @ModelAttribute("preloadUser")
    public MemberUser getUser(@RequestParam(value = "id", required = false) Long id) {
        if (id != null) {
            return memberAccountService.getUser(id);
        }
        return null;
    }

	        /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }

	        /**
     * 更新Shiro中当前用户的用户名.
     */
    private void updateCurrentUserName(String userName) {
        ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        user.name = userName;
    }
}
